<template>
  <div class="score-statistics-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>成绩统计</span>
          <el-button type="primary" @click="fetchStatistics">
            刷新
          </el-button>
        </div>
      </template>

      <!-- 试卷选择 -->
      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="试卷">
          <el-select
            v-model="queryForm.paperId"
            placeholder="请选择试卷（留空查看全部）"
            clearable
            filterable
            style="width: 300px"
            @change="handleQuery"
          >
            <el-option
              v-for="paper in paperOptions"
              :key="paper.id"
              :label="paper.name"
              :value="paper.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-divider />

      <!-- 统计卡片 -->
      <el-row :gutter="20" v-if="statistics.length > 0" class="stats-row">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="stat in statistics" :key="stat.paperId">
          <div class="stat-card-wrapper">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-card-header">
                <div class="stat-icon">
                  <el-icon :size="32"><Document /></el-icon>
                </div>
                <div class="stat-title">{{ stat.paperName }}</div>
              </div>
              <div class="stat-content">
                <div class="stat-row">
                  <div class="stat-info">
                    <el-icon class="stat-info-icon"><User /></el-icon>
                    <span class="stat-label">参考人数</span>
                  </div>
                  <span class="stat-value">{{ stat.scoredCount }}</span>
                </div>
                <div class="stat-row">
                  <div class="stat-info">
                    <el-icon class="stat-info-icon score-avg-icon"><TrendCharts /></el-icon>
                    <span class="stat-label">平均分</span>
                  </div>
                  <span class="stat-value score-avg">{{ stat.avgScore.toFixed(2) }}</span>
                </div>
                <div class="stat-row">
                  <div class="stat-info">
                    <el-icon class="stat-info-icon score-max-icon"><ArrowUp /></el-icon>
                    <span class="stat-label">最高分</span>
                  </div>
                  <span class="stat-value score-max">{{ stat.maxScore.toFixed(2) }}</span>
                </div>
                <div class="stat-row">
                  <div class="stat-info">
                    <el-icon class="stat-info-icon score-min-icon"><ArrowDown /></el-icon>
                    <span class="stat-label">最低分</span>
                  </div>
                  <span class="stat-value score-min">{{ stat.minScore.toFixed(2) }}</span>
                </div>
                <div class="stat-row">
                  <div class="stat-info">
                    <el-icon class="stat-info-icon score-pass-icon"><CircleCheck /></el-icon>
                    <span class="stat-label">通过率</span>
                  </div>
                  <span class="stat-value score-pass">{{ stat.passRate.toFixed(2) }}%</span>
                </div>
              </div>
              <div class="stat-footer">
                <el-progress 
                  :percentage="stat.passRate" 
                  :color="getProgressColor(stat.passRate)"
                  :show-text="false"
                  :stroke-width="6"
                />
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>

      <div v-loading="loading" style="min-height: 200px;">
        <el-empty v-if="statistics.length === 0 && !loading" description="暂无统计数据" />
      </div>

      <el-divider v-if="statistics.length > 0" />

      <!-- 图表区域 -->
      <div v-if="statistics.length > 0" class="charts-container">
        <!-- 平均分对比柱状图 -->
        <el-card class="chart-card">
          <template #header>
            <span>各试卷平均分对比</span>
          </template>
          <div ref="avgScoreChartRef" class="chart" style="height: 400px;"></div>
        </el-card>

        <!-- 通过率对比柱状图 -->
        <el-card class="chart-card">
          <template #header>
            <span>各试卷通过率对比</span>
          </template>
          <div ref="passRateChartRef" class="chart" style="height: 400px;"></div>
        </el-card>

        <!-- 分数段分布饼图 -->
        <el-card class="chart-card" v-if="currentPaperStat">
          <template #header>
            <span>分数段分布（{{ currentPaperStat.paperName }}）</span>
          </template>
          <div ref="scoreDistributionChartRef" class="chart" style="height: 400px;"></div>
        </el-card>

        <!-- 分数段堆叠柱状图 -->
        <el-card class="chart-card">
          <template #header>
            <span>各试卷分数段分布</span>
          </template>
          <div ref="scoreSegmentChartRef" class="chart" style="height: 400px;"></div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, User, TrendCharts, ArrowUp, ArrowDown, CircleCheck } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getStatistics, type StatisticsData } from '../../api/exam'
import { getPaperList, type PaperInfo } from '../../api/paper'
import { useUserStore } from '../../store/user'

const userStore = useUserStore()
const loading = ref(false)
const statistics = ref<StatisticsData[]>([])
const paperOptions = ref<PaperInfo[]>([])
const queryForm = reactive({
  paperId: null as number | null
})

const avgScoreChartRef = ref<HTMLDivElement | null>(null)
const passRateChartRef = ref<HTMLDivElement | null>(null)
const scoreDistributionChartRef = ref<HTMLDivElement | null>(null)
const scoreSegmentChartRef = ref<HTMLDivElement | null>(null)

let avgScoreChart: echarts.ECharts | null = null
let passRateChart: echarts.ECharts | null = null
let scoreDistributionChart: echarts.ECharts | null = null
let scoreSegmentChart: echarts.ECharts | null = null

// 当前选中的试卷统计（用于饼图）
const currentPaperStat = computed(() => {
  if (queryForm.paperId && statistics.value.length > 0) {
    return statistics.value.find(s => s.paperId === queryForm.paperId)
  }
  return statistics.value.length > 0 ? statistics.value[0] : null
})

// 获取统计数据
const fetchStatistics = async () => {
  loading.value = true
  try {
    const res = await getStatistics(queryForm.paperId || undefined)
    statistics.value = res.data || []
    if (statistics.value.length > 0) {
      await nextTick()
      initCharts()
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取统计数据失败')
  } finally {
    loading.value = false
  }
}

// 获取试卷列表
const fetchPaperList = async () => {
  try {
    const res = await getPaperList({
      page: 1,
      size: 1000,
      teacherId: userStore.isAdmin ? undefined : (userStore.userId ? parseInt(userStore.userId) : undefined)
    })
    paperOptions.value = res.data.data || []
  } catch (error) {
    ElMessage.error('获取试卷列表失败')
  }
}

// 初始化图表
const initCharts = () => {
  if (statistics.value.length === 0) return

      // 平均分对比图
      if (avgScoreChartRef.value) {
        avgScoreChart = echarts.init(avgScoreChartRef.value)
        const avgScoreOption = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            backgroundColor: 'rgba(50, 50, 50, 0.9)',
            borderColor: '#409eff',
            borderWidth: 1,
            textStyle: {
              color: '#fff'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: statistics.value.map(s => s.paperName),
            axisLabel: {
              rotate: 45,
              interval: 0,
              color: '#606266'
            },
            axisLine: {
              lineStyle: {
                color: '#e4e7ed'
              }
            }
          },
          yAxis: {
            type: 'value',
            name: '平均分',
            nameTextStyle: {
              color: '#909399'
            },
            axisLabel: {
              color: '#606266'
            },
            axisLine: {
              lineStyle: {
                color: '#e4e7ed'
              }
            },
            splitLine: {
              lineStyle: {
                color: '#f0f0f0',
                type: 'dashed'
              }
            }
          },
          series: [{
            name: '平均分',
            type: 'bar',
            data: statistics.value.map(s => parseFloat(s.avgScore.toFixed(2))),
            barWidth: '60%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#409eff' },
                { offset: 1, color: '#188df0' }
              ]),
              borderRadius: [4, 4, 0, 0]
            },
            label: {
              show: true,
              position: 'top',
              color: '#303133',
              fontWeight: 'bold'
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(64, 158, 255, 0.5)'
              }
            }
          }]
        }
        avgScoreChart.setOption(avgScoreOption)
      }

      // 通过率对比图
      if (passRateChartRef.value) {
        passRateChart = echarts.init(passRateChartRef.value)
        const passRateOption = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            backgroundColor: 'rgba(50, 50, 50, 0.9)',
            borderColor: '#67c23a',
            borderWidth: 1,
            textStyle: {
              color: '#fff'
            },
            formatter: '{b}<br/>{a}: {c}%'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: statistics.value.map(s => s.paperName),
            axisLabel: {
              rotate: 45,
              interval: 0,
              color: '#606266'
            },
            axisLine: {
              lineStyle: {
                color: '#e4e7ed'
              }
            }
          },
          yAxis: {
            type: 'value',
            name: '通过率(%)',
            max: 100,
            nameTextStyle: {
              color: '#909399'
            },
            axisLabel: {
              color: '#606266',
              formatter: '{value}%'
            },
            axisLine: {
              lineStyle: {
                color: '#e4e7ed'
              }
            },
            splitLine: {
              lineStyle: {
                color: '#f0f0f0',
                type: 'dashed'
              }
            }
          },
          series: [{
            name: '通过率',
            type: 'bar',
            data: statistics.value.map(s => parseFloat(s.passRate.toFixed(2))),
            barWidth: '60%',
            itemStyle: {
              color: function(params: any) {
                const value = params.value
                if (value >= 90) return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#95d475' },
                  { offset: 1, color: '#67c23a' }
                ])
                if (value >= 80) return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#85ceff' },
                  { offset: 1, color: '#409eff' }
                ])
                if (value >= 60) return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#f0c78a' },
                  { offset: 1, color: '#e6a23c' }
                ])
                return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#f78989' },
                  { offset: 1, color: '#f56c6c' }
                ])
              },
              borderRadius: [4, 4, 0, 0]
            },
            label: {
              show: true,
              position: 'top',
              color: '#303133',
              fontWeight: 'bold',
              formatter: '{c}%'
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(103, 194, 58, 0.5)'
              }
            }
          }]
        }
        passRateChart.setOption(passRateOption)
      }

      // 分数段分布饼图（单个试卷）
      if (scoreDistributionChartRef.value && currentPaperStat.value) {
        scoreDistributionChart = echarts.init(scoreDistributionChartRef.value)
        const stat = currentPaperStat.value
        const scoreDistributionOption = {
          tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(50, 50, 50, 0.9)',
            borderColor: '#409eff',
            borderWidth: 1,
            textStyle: {
              color: '#fff'
            },
            formatter: '{a} <br/>{b}: {c}人 ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            top: 'middle',
            textStyle: {
              color: '#606266',
              fontSize: 14
            }
          },
          series: [{
            name: '人数',
            type: 'pie',
            radius: ['45%', '75%'],
            center: ['60%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 8,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}\n{c}人 ({d}%)',
              fontSize: 12,
              color: '#303133'
            },
            labelLine: {
              show: true,
              length: 15,
              length2: 10
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 14,
                fontWeight: 'bold'
              },
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            data: [
              { value: stat.excellentCount, name: '优秀(90-100)', itemStyle: { color: '#67c23a' } },
              { value: stat.goodCount, name: '良好(80-89)', itemStyle: { color: '#409eff' } },
              { value: stat.passLowCount, name: '及格(60-79)', itemStyle: { color: '#e6a23c' } },
              { value: stat.failCount, name: '不及格(<60)', itemStyle: { color: '#f56c6c' } }
            ],
            animationType: 'scale',
            animationEasing: 'elasticOut',
            animationDelay: function (idx: number) {
              return idx * 100
            }
          }]
        }
        scoreDistributionChart.setOption(scoreDistributionOption)
      }

      // 分数段堆叠柱状图（所有试卷）
      if (scoreSegmentChartRef.value) {
        scoreSegmentChart = echarts.init(scoreSegmentChartRef.value)
        const scoreSegmentOption = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            backgroundColor: 'rgba(50, 50, 50, 0.9)',
            borderColor: '#409eff',
            borderWidth: 1,
            textStyle: {
              color: '#fff'
            }
          },
          legend: {
            data: ['优秀(90-100)', '良好(80-89)', '及格(60-79)', '不及格(<60)'],
            top: 'top',
            textStyle: {
              color: '#606266',
              fontSize: 14
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            top: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: statistics.value.map(s => s.paperName),
            axisLabel: {
              rotate: 45,
              interval: 0,
              color: '#606266'
            },
            axisLine: {
              lineStyle: {
                color: '#e4e7ed'
              }
            }
          },
          yAxis: {
            type: 'value',
            name: '人数',
            nameTextStyle: {
              color: '#909399'
            },
            axisLabel: {
              color: '#606266'
            },
            axisLine: {
              lineStyle: {
                color: '#e4e7ed'
              }
            },
            splitLine: {
              lineStyle: {
                color: '#f0f0f0',
                type: 'dashed'
              }
            }
          },
          series: [
            {
              name: '优秀(90-100)',
              type: 'bar',
              stack: 'score',
              data: statistics.value.map(s => s.excellentCount),
              itemStyle: { 
                color: '#67c23a',
                borderRadius: [4, 4, 0, 0]
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(103, 194, 58, 0.5)'
                }
              }
            },
            {
              name: '良好(80-89)',
              type: 'bar',
              stack: 'score',
              data: statistics.value.map(s => s.goodCount),
              itemStyle: { 
                color: '#409eff',
                borderRadius: [0, 0, 0, 0]
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(64, 158, 255, 0.5)'
                }
              }
            },
            {
              name: '及格(60-79)',
              type: 'bar',
              stack: 'score',
              data: statistics.value.map(s => s.passLowCount),
              itemStyle: { 
                color: '#e6a23c',
                borderRadius: [0, 0, 0, 0]
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(230, 162, 60, 0.5)'
                }
              }
            },
            {
              name: '不及格(<60)',
              type: 'bar',
              stack: 'score',
              data: statistics.value.map(s => s.failCount),
              itemStyle: { 
                color: '#f56c6c',
                borderRadius: [0, 0, 4, 4]
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(245, 108, 108, 0.5)'
                }
              }
            }
          ]
        }
        scoreSegmentChart.setOption(scoreSegmentOption)
      }
}

// 查询
const handleQuery = () => {
  fetchStatistics()
}

// 重置
const handleReset = () => {
  queryForm.paperId = null
  handleQuery()
}

// 获取进度条颜色
const getProgressColor = (percentage: number) => {
  if (percentage >= 90) return '#67c23a'
  if (percentage >= 80) return '#409eff'
  if (percentage >= 60) return '#e6a23c'
  return '#f56c6c'
}

// 窗口大小改变时重新调整图表大小
const handleResize = () => {
  avgScoreChart?.resize()
  passRateChart?.resize()
  scoreDistributionChart?.resize()
  scoreSegmentChart?.resize()
}

onMounted(() => {
  fetchPaperList()
  fetchStatistics()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  avgScoreChart?.dispose()
  passRateChart?.dispose()
  scoreDistributionChart?.dispose()
  scoreSegmentChart?.dispose()
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.score-statistics-container {
  padding: 20px;
  overflow: visible;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 60px);
}

.score-statistics-container :deep(.el-card) {
  overflow: visible;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.score-statistics-container :deep(.el-card):hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.score-statistics-container :deep(.el-card__body) {
  overflow: visible;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.search-form {
  margin-bottom: 24px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
}

.stats-row {
  margin-bottom: 24px;
}

.stat-card-wrapper {
  height: 100%;
}

.stat-card {
  height: 100%;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
  border: 1px solid #e4e7ed;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
}

.stat-card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f0f0;
}

.stat-icon {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  border-radius: 12px;
  color: #fff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.stat-title {
  flex: 1;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.5;
}

.stat-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 16px;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 12px;
  background: #fafafa;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.stat-row:hover {
  background: #f0f0f0;
  transform: translateX(4px);
}

.stat-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-info-icon {
  font-size: 18px;
  color: #909399;
}

.stat-info-icon.score-avg-icon {
  color: #409eff;
}

.stat-info-icon.score-max-icon {
  color: #67c23a;
}

.stat-info-icon.score-min-icon {
  color: #e6a23c;
}

.stat-info-icon.score-pass-icon {
  color: #f56c6c;
}

.stat-label {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.stat-value {
  font-weight: 700;
  font-size: 16px;
  color: #303133;
}

.score-avg {
  color: #409eff;
  font-size: 18px;
}

.score-max {
  color: #67c23a;
  font-size: 18px;
}

.score-min {
  color: #e6a23c;
  font-size: 18px;
}

.score-pass {
  color: #f56c6c;
  font-size: 18px;
}

.stat-footer {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.charts-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.chart-card {
  margin-bottom: 0;
  background: #fff;
  border-radius: 12px;
  padding: 20px;
}

.chart-card :deep(.el-card__header) {
  padding: 16px 20px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #f0f0f0;
}

.chart {
  width: 100%;
}

@media (max-width: 768px) {
  .stats-row {
    margin-bottom: 16px;
  }
  
  .stat-card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .stat-title {
    width: 100%;
  }
}
</style>

